import { ApiObject, fetcherResult } from 'amis/lib/types'
import BaseEnumValue from '@/core/utils/BaseEnumValue'
import BaseEnum from '@/core/utils/BaseEnum'

class AmisUtils {
	defaultResponseAdaptor = (payload: object, response: fetcherResult, api: ApiObject): any => {
		return {
			status: response.data?.code,
			msg: response.data?.message,
			data: response.data?.data,
		}
	}

	getSelectResponseAdaptor = (
		labelFieldName: string,
		valueFieldName: string,
	): ((payload: object, response: fetcherResult, api: ApiObject) => any) => {
		return (payload: object, response: fetcherResult, api: ApiObject): any => {
			const newData = { value: undefined, options: [] as any[] }
			if (response.data?.data.hasOwnProperty('items')) {
				const items: [] = (response.data.data as any)['items']
				if (items.length > 0) {
					items.forEach(value => {
						newData.options.push({ label: value[labelFieldName], value: value[valueFieldName] })
					})
				}
			}
			return {
				status: response.data?.status,
				msg: response.data?.msg,
				data: newData,
			}
		}
	}

	getSelectOptionsFromBaseEnumValues = <T>(...values: BaseEnumValue<T>[]): { label: string; value: T }[] => {
		return values.map(value => {
			return {
				label: value.getDesc(),
				value: value.getCode(),
			}
		})
	}

	getSelectOptionsFromBaseEnum = <T>(baseEnum: BaseEnum<T>): { label: string; value: T }[] => {
		return baseEnum.getAll().map(value => {
			return {
				label: value.getDesc(),
				value: value.getCode(),
			}
		})
	}

	/**
	 * 获取判断变量是否存在values中
	 * @param propertyName 变量名
	 * @param values
	 */
	getIsInValuesExpression = (propertyName: string, values: string[]): string => {
		let expression = 'false'
		values.forEach((value, index, array) => {
			expression = `${expression} || this.${propertyName} === '${value}'`
		})
		return `(${expression})`
	}
}

export default new AmisUtils()
